package cn.tradewin.advisor.pages.account;

import org.apache.shiro.authc.credential.PasswordService;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.slf4j.Logger;

import cn.tradewin.advisor.commons.AdvisorSymbols;
import cn.tradewin.advisor.commons.selectmodel.CodeLabelSelectModel;
import cn.tradewin.advisor.commons.util.CodeTableSymbols;
import cn.tradewin.advisor.commons.util.LanguageSymbols;
import cn.tradewin.advisor.persist.model.Account;
import cn.tradewin.advisor.persist.model.Users;
import cn.tradewin.advisor.persist.services.AccountService;
import cn.tradewin.advisor.persist.services.CodetableService;
import cn.tradewin.advisor.persist.services.CustomerService;
import cn.tradewin.advisor.persist.services.DeptService;
import cn.tradewin.advisor.persist.services.JobService;

public class AddAccount {

	@Inject
	private AccountService accountService;

	@Inject
	private PasswordService passwordService;
	
	@Property
	private Account account;
	
	@Property
	private SelectModel deptModel;
	
	@Property
	private SelectModel customerModel;
	
	@Property
	private SelectModel etypeModel;
	
	@Property
	private SelectModel jobModel;
	
	@Inject
	private CodetableService codetablelService;
	
	@Inject
	private CustomerService customerService;

	@Inject
	private DeptService deptService;
	
	@Inject
	private JobService jobService;
	
	@Inject
	@Symbol(AdvisorSymbols.DEFAULT_PASSWORD)
	private String defaultPassword;

	@Inject
	private Logger log;
	
	
	void onPrepareForRender() {
		customerModel = new CodeLabelSelectModel(customerService.getAllCustomerOptions());
		deptModel = new CodeLabelSelectModel(deptService.getAllDeptsOptions());
		etypeModel = new CodeLabelSelectModel(codetablelService.listCategory(CodeTableSymbols.EMPLOYEE_TYPE, LanguageSymbols.ZH));
		jobModel = new CodeLabelSelectModel(jobService.getJobs());
	}
	
	@Log
	void onPrepare() {
		if (account == null) {
			account = new Account();
			account.setUser(new Users());
		}
	}

	@Log
	Object onSubmit() {
		try {
			account.getUser().setId(account.getId());
			account.getUser().setPassword(passwordService.encryptPassword(defaultPassword));
			account.getUser().setPasswordSalt("123456");
			accountService.addAccount(account);
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		return AccountBoard.class;
	}

}
